﻿using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Web;
using System.Web.Mvc;

namespace Hasiu.Mvc.Controllers.Tools
{
    public class YzmToolsController : Controller
    {
        public ActionResult Index()
        {
            var checkCode = GetRandomCode(4);
            Response.Cookies.Add(new HttpCookie("checkcode", checkCode.ToLower().Encrypt()));
            SetPageNoCache();
            CreateImage(checkCode);
            return new EmptyResult();
        }

        /// <summary>
        /// 设置页面不被缓存
        /// </summary>
        private void SetPageNoCache()
        {
            Response.Buffer = true;
            Response.ExpiresAbsolute = DateTime.Now.AddSeconds(-1);
            Response.Expires = 0;
            Response.CacheControl = "no-cache";
            Response.AppendHeader("Pragma", "No-Cache");
        }

        private static string GetRandomCode(int codeCount)
        {
            const string allChar = "0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,i,J,K,M,N,P,Q,R,S,T,U,W,X,Y,Z";
            var allCharArray = allChar.Split(',');
            var randomCode = "";
            var temp = -1;

            var rand = new Random();
            for (var i = 0; i < codeCount; i++)
            {
                if (temp != -1)
                {
                    rand = new Random(temp*i*((int) DateTime.Now.Ticks));
                }

                var t = rand.Next(33);

                while (temp == t)
                {
                    t = rand.Next(33);
                }

                temp = t;
                randomCode += allCharArray[t];
            }

            return randomCode;
        }

        private void CreateImage(string checkCode)
        {
            var iwidth = (checkCode.Length*14);
            var image = new Bitmap(iwidth, 20);
            var g = Graphics.FromImage(image);
            var f = new Font("宋体 ", 10); //, System.Drawing.FontStyle.Bold);
            var b = new SolidBrush(ColorTranslator.FromHtml("#333333"));
            var r = new SolidBrush(ColorTranslator.FromHtml("#990000"));

            //g.FillRectangle(new System.Drawing.SolidBrush(Color.Blue),0,0,image.Width, image.Height);
            //			g.Clear(Color.AliceBlue);//背景色

            g.Clear(ColorTranslator.FromHtml("#ffffff")); //背景色

            var ch = checkCode.ToCharArray();
            for (var i = 0; i < ch.Length; i++)
            {
                if (ch[i] >= '0' && ch[i] <= '9')
                {
                    //数字用红色显示
                    g.DrawString(ch[i].ToString(), f, r, 3 + (i*12), 3);
                }
                else
                {
                    //字母用黑色显示
                    g.DrawString(ch[i].ToString(), f, b, 3 + (i*12), 3);
                }
            }

            //for循环用来生成一些随机的水平线
            //Pen blackPen = new Pen(Color.Black, 0);
            //Random rand = new Random();
            //for (int i=0;i< 5;i++)
            //{
            //    int y = rand.Next(image.Height);
            //    g.DrawLine(blackPen,0,y,image.Width,y);
            //}

            var ms = new MemoryStream();
            image.Save(ms, ImageFormat.Jpeg);
            //history back 不重复 
            Response.Cache.SetNoStore(); //这一句 		
            Response.ClearContent();
            Response.ContentType = "image/Jpeg";
            Response.BinaryWrite(ms.ToArray());
            g.Dispose();
            image.Dispose();
        }
    }
}